package com.baitiaojun.moments.handler.canal;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.domain.moments.UserVideoMoments;
import com.baitiaojun.api.domain.video.Video;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.vo.JsonRes;
import com.baitiaojun.moments.feign.VideoFeign;
import com.baitiaojun.moments.service.MomentsService;
import com.baitiaojun.moments.service.VideoMomentsService;
import com.baitiaojun.moments.support.RedisSupport;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @类名 SyncRedisHandler
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/2/13 17:40
 * @版本 1.0
 */
@Component
public class SyncRedisHandler {

    @Autowired
    private RedisSupport redisSupport;

    @Autowired
    private MomentsService momentsService;

    @Autowired
    private VideoMomentsService videoMomentsService;

    @Autowired
    private VideoFeign videoFeign;

    @SneakyThrows
    protected void update(Long videoId) {
        Long videoMomentId = videoMomentsService.getVideoMomentsIdByVideoId(videoId);
        Long userId = momentsService.getUserMoments(videoMomentId).getUserid();
        Object userVideoMoment = redisSupport.getHash("subscribed" + userId, String.valueOf(videoMomentId));
        //获取moments
        UserVideoMoments userVideoMoments = JSONObject.parseObject(JSONObject.toJSONString(userVideoMoment), UserVideoMoments.class);
        Video video = userVideoMoments.getVideo();
        video.setId(video.getId());
        video.setTitle(video.getTitle());
        video.setThumbnail(video.getThumbnail());
        video.setDuration(video.getDuration());
        //获取VideoComment的数量
        Integer videoCommentCount = videoFeign.getVideoCommentCount(videoId);
        //获取VideoLike的数量
        JsonRes resVideoLike = videoFeign.getVideoLike(videoId);
        if (resVideoLike.get("status").equals(500)) {
            throw new ConditionException("获取视频点赞失败");
        }
        Map<String, Object> map = (Map<String, Object>) resVideoLike.get("data");
        Integer likeCount = (Integer) map.get("count");
        //获取VideoView的数量
        JsonRes resVideoView = videoFeign.getVideoViewCount(videoId);
        if (resVideoView.get("status").equals(500)) {
            throw new ConditionException("获取视频观看记录失败");
        }
        Integer viewCount = (Integer) resVideoView.get("data");
        //添加最新记录
        video.setCommentCount(videoCommentCount == null? 0 : videoCommentCount);
        video.setLickCount(likeCount == null? 0 : likeCount);
        video.setViewCount(viewCount == null? 0 : viewCount);
        userVideoMoments.setVideo(video);
        redisSupport.setHash("subscribed" + userId, String.valueOf(videoMomentId), userVideoMoments);
    }
}
